package com.hoshiicloud.user.controller.organization;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.user.entity.organization.ComOrganization;
import com.hoshiicloud.user.param.organization.ComOrganizationAddParam;
import com.hoshiicloud.user.param.organization.ComOrganizationQueryParam;
import com.hoshiicloud.user.param.organization.ComOrganizationUpdateParam;
import com.hoshiicloud.user.service.organization.ComOrganizationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 供应商 控制器
 * </p>
 *
 * @author campchen
 * @since 2019-04-28
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/organization/com-organization")
@Api(value = "SAAS租户供应商", tags = {"SAAS租户供应商"})
@ApiSort(10)
public class ComOrganizationController {
    @Autowired
    private ComOrganizationService comOrganizationService;


    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 分页查询供应商
     */
    @ApiOperation(value = "分页查询租户供应商")
    @PostMapping("/getPage")
    public Response page(@RequestBody @Valid ComOrganizationQueryParam param) {
        try {
            QueryWrapper<ComOrganization> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq((param.getCompanyId() != null && param.getCompanyId() != 0), ComOrganization::getCompanyId, param.getCompanyId())
                    .eq((param.getDepartmentId() != null && param.getDepartmentId() != 0), ComOrganization::getDepartmentId, param.getDepartmentId())
                    .eq((param.getOrganizationTypeId() != null), ComOrganization::getOrganizationTypeId, param.getOrganizationTypeId())
                    .eq((param.getType() != null), ComOrganization::getType, param.getType())
                    .eq((param.getParentId() != null), ComOrganization::getParentId, param.getParentId())
                    .eq(StringUtils.isNotBlank(param.getName()), ComOrganization::getName, param.getName())
                    .eq(StringUtils.isNotBlank(param.getCharge()), ComOrganization::getCharge, param.getCharge())
                    .eq(StringUtils.isNotBlank(param.getIdCard()), ComOrganization::getIdCard, param.getIdCard())
                    .eq((param.getAccountType() != null), ComOrganization::getType, param.getType())
                    .eq(StringUtils.isNotBlank(param.getAccountName()), ComOrganization::getAccountName, param.getAccountName())
                    .eq(StringUtils.isNotBlank(param.getBankNumber()), ComOrganization::getBankNumber, param.getBankNumber())
                    .eq(StringUtils.isNotBlank(param.getBankName()), ComOrganization::getBankName, param.getBankName())
                    .eq(StringUtils.isNotBlank(param.getBankAddress()), ComOrganization::getBankAddress, param.getBankAddress())
                    .eq(StringUtils.isNotBlank(param.getTaxation()), ComOrganization::getTaxation, param.getTaxation())
                    .eq(StringUtils.isNotBlank(param.getPiaohao()), ComOrganization::getPiaohao, param.getPiaohao())
                    .eq(StringUtils.isNotBlank(param.getGoodsAddress()), ComOrganization::getGoodsAddress, param.getGoodsAddress())
                    .eq(StringUtils.isNotBlank(param.getWhouseAddress()), ComOrganization::getWhouseAddress, param.getWhouseAddress())
                    .eq((param.getPaymentId() != null && param.getPaymentId() != 0), ComOrganization::getPaymentId, param.getPaymentId())
                    .eq(StringUtils.isNotBlank(param.getTelphone()), ComOrganization::getTelphone, param.getTelphone())
                    .eq(StringUtils.isNotBlank(param.getMobile()), ComOrganization::getMobile, param.getMobile())
                    .eq(StringUtils.isNotBlank(param.getFax()), ComOrganization::getFax, param.getFax())
                    .eq(StringUtils.isNotBlank(param.getHome()), ComOrganization::getHome, param.getHome())
                    .eq(StringUtils.isNotBlank(param.getEmail()), ComOrganization::getEmail, param.getEmail())
                    .eq(StringUtils.isNotBlank(param.getAddress()), ComOrganization::getAddress, param.getAddress())
                    .eq((param.getApplyType() != null), ComOrganization::getApplyType, param.getApplyType())
                    .eq(StringUtils.isNotBlank(param.getApplyIdNumber()), ComOrganization::getApplyIdNumber, param.getApplyIdNumber())
                    .eq(StringUtils.isNotBlank(param.getApplyName()), ComOrganization::getApplyName, param.getApplyName())
                    .eq(StringUtils.isNotBlank(param.getApplyAddress()), ComOrganization::getApplyAddress, param.getApplyAddress())
                    .eq(StringUtils.isNotBlank(param.getApplyIssuedby()), ComOrganization::getApplyIssuedby, param.getApplyIssuedby())
                    .eq(StringUtils.isNotBlank(param.getApplySex()), ComOrganization::getApplySex, param.getApplySex())
                    .eq(StringUtils.isNotBlank(param.getApplyBirthplace()), ComOrganization::getApplyBirthplace, param.getApplyBirthplace())
                    .eq(StringUtils.isNotBlank(param.getApplyBirthday()), ComOrganization::getApplyBirthday, param.getApplyBirthday())
                    .eq(StringUtils.isNotBlank(param.getApplyIdFront()), ComOrganization::getApplyIdFront, param.getApplyIdFront())
                    .eq(StringUtils.isNotBlank(param.getApplyIdBack()), ComOrganization::getApplyIdBack, param.getApplyIdBack())
                    .eq((param.getChargeTelphone() != null), ComOrganization::getChargeTelphone, param.getChargeTelphone())
                    .eq((param.getChargeWeixin() != null), ComOrganization::getChargeWeixin, param.getChargeWeixin())
                    .eq((param.getChargeEmail() != null), ComOrganization::getChargeEmail, param.getChargeEmail())
                    .eq((param.getProvince() != null), ComOrganization::getProvince, param.getProvince())
                    .eq(StringUtils.isNotBlank(param.getProvinceName()), ComOrganization::getProvinceName, param.getProvinceName())
                    .eq((param.getCity() != null), ComOrganization::getCity, param.getCity())
                    .eq(StringUtils.isNotBlank(param.getCityName()), ComOrganization::getCityName, param.getCityName())
                    .eq((param.getDistrict() != null), ComOrganization::getDistrict, param.getDistrict())
                    .eq(StringUtils.isNotBlank(param.getDistrictName()), ComOrganization::getDistrictName, param.getDistrictName())
                    .eq((param.getStreet() != null), ComOrganization::getStreet, param.getStreet())
                    .eq(StringUtils.isNotBlank(param.getStreetName()), ComOrganization::getStreetName, param.getStreetName())
                    .eq((param.getAvailableBalance() != null), ComOrganization::getAvailableBalance, param.getAvailableBalance())
                    .eq((param.getAccountBalance() != null), ComOrganization::getAccountBalance, param.getAccountBalance())
                    .eq((param.getFreezingAmount() != null), ComOrganization::getFreezingAmount, param.getFreezingAmount())
                    .eq(StringUtils.isNotBlank(param.getContacts()), ComOrganization::getContacts, param.getContacts())
                    .eq(StringUtils.isNotBlank(param.getInvitedCode()), ComOrganization::getInvitedCode, param.getInvitedCode())
                    .eq(StringUtils.isNotBlank(param.getWeixin()), ComOrganization::getWeixin, param.getWeixin())
                    .eq(StringUtils.isNotBlank(param.getProfile()), ComOrganization::getProfile, param.getProfile())
                    .eq((param.getStatus() != null), ComOrganization::getStatus, param.getStatus());
            Page<ComOrganization> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = param.toString() + ",Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize() + "}";
            return Response.data(comOrganizationService.getPage(page, queryWrapper, key));
        } catch (NumberFormatException e) {
            log.error("分页查询租户供应商异常", e);
            return Response.failed("分页查询租户供应商异常");
        } catch (Exception e1) {
            log.error("分页查询租户供应商异常", e1);
            return Response.failed(e1.getMessage());
        }

    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 根据id查询供应商
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询租户供应商")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response queryById(@PathVariable("id") Long id) {
        return Response.data(comOrganizationService.getById(id));
    }

    /**
     * @Author:campchen
     * @Description: StringUtils.join(ids, " ") 为缓存中添加唯一KEY  如不合适可选择更好方法
     * @Date:上午 10:18 2019/5/11
     * @Param: ids
     * @return: com.hoshiicloud.common.rpc.Response
     */
    @ApiOperation(value = "根据id集合查询租户供应商")
    @GetMapping("/Ids")
    public Response Ids(@RequestParam List<Long> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            ids.sort(null);
            return Response.data(comOrganizationService.getByIds(ids, StringUtils.join(ids, "")));
        } else {
            return Response.data(null);
        }
    }


    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增租户供应商")
    public Response save(@RequestBody @Valid ComOrganizationAddParam param) {
        ComOrganization data;
        try {
            data = BeanUtils.covertType(param, ComOrganization.class);
        } catch (Exception e) {
            log.error("新增租户供应商Bean转换异常", e);
            return Response.failed("新增租户供应商Bean转换异常");
        }
        return Response.data(comOrganizationService.insert(data));

    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改供应商
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改租户供应商")
    public Response update(@RequestBody @Valid ComOrganizationUpdateParam param) {
        ComOrganization data;
        try {
            data = BeanUtils.covertType(param, ComOrganization.class);
        } catch (Exception e) {
            log.error("修改租户供应商Bean转换异常", e);
            return Response.failed("新增租户供应商Bean转换异常");
        }
        return Response.data(comOrganizationService.updateById(data));
    }

    /**
     * @Author:campchen
     * @Description: 供应商审批接口 0-未审批 1-已审批 2-已终止合作
     * @Date:上午 10:26 2019/5/24
     * @Param: id, sataus
     * @return: Response
     */
    @PutMapping("/comApproval")
    @ApiOperation(value = "租户供应商审批")
    public Response comApproval(@RequestParam Long id, @RequestParam Integer status) {
        return Response.data(comOrganizationService.updateById(id, status));
    }

    @DeleteMapping("/deleteById")
    @ApiOperation(value = "租户供应商删除")
    public Response deleteById(@RequestParam Long id){
        return Response.data(comOrganizationService.deleteById(id));
    }

    @GetMapping("/selectOrganizationByMemberId/{memberId}")
    @ApiOperation(value = "根据MemberId查询所关联的供应商 部分信息")
    public Response selectOrganizationByMemberId(@PathVariable("memberId") Long memberId){
        return Response.data(comOrganizationService.selectOrganizationByMemberId(memberId));
    }


    @GetMapping("/find/{name}")
    @ApiOperation(value = "查询", notes = "根据名称查询租户供应商信息", consumes = MediaType.ALL_VALUE)
    public Response findByName(@PathVariable("name") String name) {
        List<ComOrganization> list=comOrganizationService.selectOrgByName(name);
        if (list.size()>0){
            return Response.data("已存在");
        }
        return Response.data("名称未使用");
    }
}
